package com.youdianstar.app.ui

import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.*
import androidx.lifecycle.Observer

import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityRentOrderBinding

import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.MathUtil
import com.youdianstar.app.common.util.StrUtil

import com.youdianstar.app.entity.RentResult
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: RentOrderActivity
 * Author: 82149 Create: 2021/11/9 16:04
 * Changes (from 2021/11/9)
 * --------------------------------------------------
 * description: 租借进度条+结果页面
 * ---------------------------------------------------
 *
 */
class RentOrderActivity : BaseActivity<ActivityRentOrderBinding, ScanViewModel>() {
    override fun layoutId(): Int = R.layout.activity_rent_order

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): ScanViewModel {
        val model: ScanViewModel by viewModel()
        return model
    }

    private var orderNo: String = ""
    //标记租借成功
    private var rentSuccess = false
    //接口成功,延时5s调用查询接口
    private val QUERY_ACTION_CODE = 0x39
    private val mHandler = Handler(Looper.myLooper()!!) {
        if (it.what == QUERY_ACTION_CODE) {
            if (!StrUtil.isEmpty(orderNo))
                mViewModel.queryRentResult(orderNo)
        }
        false
    }

    override fun initData() {
        super.initData()
        mBinding.headBar.initTitle(this, "")
        mBinding.clResult.visibility = View.INVISIBLE
        mBinding.clProcess.visibility = View.VISIBLE

        //扫码页面or支付页面: 下单的获取的单号
        val order = intent.getStringExtra(Extra.IT_ORDERNO)
        order?.let {
            orderNo = it
            setStartRent(it)
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.queryResultLiveData.observe(this, object : BaseApiResultObserver<RentResult>(true) {
                override fun onDataResult(data: RentResult?) {
                    super.onDataResult(data)
                   if (null!=data){
                       if (!StrUtil.isEmpty(data.orderNo)) {
                           //停止计时
                           mViewModel.countJob?.cancel()
                           //成功动画
                           setResultSuccess()
                       } else
                           mHandler.sendEmptyMessageDelayed(QUERY_ACTION_CODE, 5000)
                   }else{
                       mHandler.sendEmptyMessageDelayed(QUERY_ACTION_CODE, 5000)
                   }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    mHandler.sendEmptyMessageDelayed(QUERY_ACTION_CODE, 5000)
                }
            })

        mViewModel.timeCountEvent.observe(this, Observer {
            LogUtil.d("-----Count:$it")
            if (it == 0)
                processAnim()
            //计时时间
            if (it in 0..59) {
                val process = MathUtil.div(it, 60, 2) * 100
                mBinding.tvProcessValue.text = "" + process.toInt() + "%"
            } else {
                mHandler.removeCallbacksAndMessages(null)
                setResultFailed()
            }
        })

        mViewModel.finishCountEvent.observe(this, Observer {
            LogUtil.d("----F-Count:$it")
            //计时时间
            if (it in 1..5) {
                mBinding.btnConfirm.text = "${getString(R.string.home_viewOrder)}($it)"
            } else {
                startActivity<OrderDetailActivity>(
                    Extra.IT_ORDERNO to orderNo,
                    Extra.IT_TYPE to 1
                ) //成功 查看订单
                finish()
            }
        })
    }

    override fun initClickEvent() {
        mBinding.btnConfirm.setOnClickListener {
            if (rentSuccess) {
                mViewModel.finishJob?.cancel()
                startActivity<OrderDetailActivity>(
                    Extra.IT_ORDERNO to orderNo,
                    Extra.IT_TYPE to 1
                ) //成功 查看订单
                finish()
            } else {
                finish() //失败 返回扫码
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages(null)
    }

    /**
     * 设置业务状态
     * --开始租借
     * @param orderNo 订单号
     */
    private fun setStartRent(orderNo: String) {
        setResultStateLayout(0)
        //请求接口,开始倒计时
        mViewModel.queryRentResult(orderNo)
        mViewModel.countTime()
    }

    /**
     * 设置业务状态
     * --租借失败
     */
    private fun setResultFailed() {
        rentSuccess = false
        //mBinding.ivAnimRent.clearAnimation() //25/02/28
        mBinding.lottieView.pauseAnimation()
//        failedAnim()
        setResultStateLayout(2)
    }

    /**
     * 设置业务状态
     * --租借成功
     */
    private fun setResultSuccess() {
        rentSuccess = true
        //mBinding.ivAnimRent.clearAnimation() //25/02/28 换动画
        mBinding.lottieView.pauseAnimation()
//        setResultStateLayout(1) //25/02/28 不显示成功,直接回主页
        //倒计时 ,需要在UI页面显示
//        mViewModel.finishCountTime()//25/02/28 不显示成功,直接回主页

        startActivity<MainActivity>() //25/02/28 回到主页
        finish()
    }

    /**
     * 设置页面状态
     * @param state 0:Renting 1:Success 2:Failed
     */
    private fun setResultStateLayout(state: Int) {
        when (state) {
            0 -> {
                mBinding.headBar.setBackUnable(isVisi = false)
                mBinding.clProcess.visibility = View.VISIBLE
                mBinding.clResult.visibility = View.INVISIBLE
                mBinding.tvProcessValue.text = "0%"
                mBinding.lottieView.setAnimation(R.raw.loading_lottie)
            }
            1 -> {
                mBinding.headBar.setBackUnable(isVisi = true)
                mBinding.clProcess.visibility = View.INVISIBLE
                mBinding.clResult.visibility = View.VISIBLE
                mBinding.tvProcessValue.text = "100%"
                mBinding.ivResult.setImageResource(R.mipmap.ic_rent_success)
                mBinding.resultTitle.text = getString(R.string.home_success)
                mBinding.resultTitle.setTextColor(getViewColor(this,R.color.color_9BB955))
                mBinding.resultContent.text = getString(R.string.home_takePBText)
            }
            2 -> {
                mBinding.headBar.setBackUnable(isVisi = true)
                mBinding.clProcess.visibility = View.INVISIBLE
                mBinding.clResult.visibility = View.VISIBLE
                mBinding.tvProcessValue.text = "0%"
                mBinding.ivResult.setImageResource(R.mipmap.ic_rent_failed)
                mBinding.resultTitle.text = getString(R.string.home_failed)
                mBinding.resultTitle.setTextColor(getViewColor(this,R.color.color_889DBB))
                mBinding.resultContent.text = getString(R.string.home_scanAgainText)
                mBinding.btnConfirm.text = getString(R.string.home_scan2rent2)
            }
            else -> {
                mBinding.clProcess.visibility = View.INVISIBLE
                mBinding.clResult.visibility = View.INVISIBLE
                mBinding.tvProcessValue.text = "0%"
            }
        }
    }

    private fun processAnim() {
        //旧动画
//        val rotateAnimator = RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
//        val lin = LinearInterpolator()
//        rotateAnimator.interpolator = lin
//        rotateAnimator.duration = 500
//        rotateAnimator.repeatCount = -1
//        rotateAnimator.fillAfter = true
//        rotateAnimator.repeatMode = Animation.RESTART
//        mBinding.ivAnimRent.animation = rotateAnimator
//        rotateAnimator.start()
        mBinding.lottieView.playAnimation()
    }

}